package com.cn.why.springcloudskills.controller;

import com.cn.why.springcloudskills.service.SkillsService;
import com.cn.why.springcloudskills.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀controller
 */
@RestController
@RequestMapping("/skills")
public class SkillsController {
    private static int corePoolSize = Runtime.getRuntime().availableProcessors();//获取当前cpu能处理线程的最大数
    //创建线程池 调整队列数 拒绝服务
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,corePoolSize+1,100, TimeUnit.SECONDS,new LinkedBlockingDeque<>(1000));

    //加入service
    @Autowired
    private SkillsService service;
    /**
     * 秒杀方法一,模拟1000个人同时秒杀一件商品的情况
     * 利用aop编程来实现线程安全
     */
    @RequestMapping("/aopLock")
    public Result startByAopLock(long seckillId, String callback){
        System.out.println("开始秒杀商品："+seckillId);
        //先删除秒杀成功，用于测试功能
        service.deleteSeckill(seckillId);
        final long killId = seckillId;
        System.out.println("开始AOP秒杀！");
        //模拟1000个线程同时抢购
        for (int i = 0; i < 1000; i++) {
            final long userId = i;
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    Result result = service.startSeckilAopLock(killId,userId);
                    System.out.println(userId+""+result.get("message"));
                }
            };
            //将线程添加到线程池中
            executor.execute(task);
        }
        try {
            Thread.sleep(5000);
            long skillsCount = service.getCountSkills(seckillId);
            System.out.println("一共秒杀出"+skillsCount);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Result.end("秒杀中，请稍等！");
    }
}
